package com.fy.service.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fy.common.model.im.MessageModel;
import com.fy.service.server.service.ImGroupService;
import com.fy.service.service.ImBrokerService;
import com.fy.service.service.MessageService;
import io.netty.channel.ChannelHandlerContext;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ImGroupServiceImpl implements ImGroupService {

    @Autowired
    private ImBrokerService imBrokerService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Value("${spring.rocketmq.consumer.brokerMessageTopic}")
    private String brokerMessageTopic;

    @Override
    public void groupChat(MessageModel message, String fromCmd, String toCmd, ChannelHandlerContext ctx) throws Exception {
        //从群缓存查询群配置


        //持久化消息后返回发送方消息发送成功
        //生成服务器的消息id
        Long sendTime = new Date().getTime();
        message.setSendTime(sendTime);
        MessageModel saveModel = new MessageModel();
        BeanUtils.copyProperties(message, saveModel);
        saveModel.setCmd(toCmd);
        messageService.saveGroupMessage(saveModel);
        //入库后生成id
        message.setMessageId(saveModel.getMessageId());
        MessageModel responseModel = new MessageModel();
        responseModel.setCmd(fromCmd);
        responseModel.setMessageId(message.getMessageId());
        responseModel.setProtocolType(message.getProtocolType());
        responseModel.setSendTime(sendTime);
        responseModel.setClientMessageId(message.getClientMessageId());
        responseModel.setToGroup(message.getToGroup());
        //通知发送方消息发送成功
        imBrokerService.push(responseModel, ctx);
        //直接把消息放入消息队列 送到路由中心去离线下发
        //Message
        rocketMQTemplate.convertAndSend(brokerMessageTopic, JSONObject.toJSONString(message));
    }
}
